package com.mu.util;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mu.exception.MuException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class RemoteHttpUtils {

    private final static int DEFAULT_READ_TIME_OUT = 60000;

    private final static int DEFAULT_CONNECTION_OUT = 30000;
    ;
    private static final String DATA = "data";
    private static final String SELECT_THIRD_LIVE_INFO = "/business-facade/api/ads/third/live/room/info";

    private static final String GET_ORDER_INFO = "/api/";
    private static final String getProductList = "/api/product/store/getProduct";

    public String selectThirdLiveRoomInfo(String moushiCoreFacadeUrl, String roomId) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("roomId", roomId);
        JSONObject asJsonObject = getAsJsonObject(moushiCoreFacadeUrl + SELECT_THIRD_LIVE_INFO, param);
        return Objects.isNull(asJsonObject.get(DATA)) ? null : asJsonObject.get(DATA).toString();
    }

    /**
     * get请求
     *
     * @param url    请求链接
     * @param params path上的参数
     * @return 回传结果
     */
    public JSONObject getAsJsonObject(String url, Map<String, Object> params) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json; charset=utf-8");

            HttpResponse response = HttpUtil.createGet(url)
                    .form(params)
                    .setReadTimeout(DEFAULT_READ_TIME_OUT)
                    .setConnectionTimeout(DEFAULT_CONNECTION_OUT)
                    .addHeaders(headers)
                    .execute();

            log.info("请求日志，请求链接：{}，返回结果：{}", url, response);
            return parseResponse(response);
        } catch (Exception e) {
            log.error("请求系统错误，请求链接：{}，系统失败原因：", url, e);
            throw new MuException("请求错误");
        }
    }

    /**
     * 解析 http 结果
     *
     * @param response 响应结果
     * @return body的内容
     */
    private JSONObject parseResponse(HttpResponse response) {
        String body = null;
        if (null == response) {
            throw new MuException("接口错误");
        }
        if (response.getStatus() != 200) {
            throw new MuException("请求错误");
        }
        body = response.body();

        return JSONObject.parseObject(body);
    }

    private JSONObject getPostJsonObject(Map<String, Object> paramMap, String requestUrl) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json; charset=utf-8");

            HttpResponse response = HttpUtil.createPost(requestUrl)
                    .body(JSON.toJSONString(paramMap))
                    .setReadTimeout(DEFAULT_READ_TIME_OUT)
                    .setConnectionTimeout(DEFAULT_CONNECTION_OUT)
                    .addHeaders(headers)
                    .execute();

            log.info("请求日志，请求链接：{}，请求参数：{}，返回结果：{}", requestUrl, paramMap, response);

            return parseResponse(response);
        } catch (Exception e) {
            log.error("请求系统错误，请求链接：{}，请求参数：{}，系统失败原因：{}", requestUrl, paramMap, e);
            throw new MuException(e.getMessage());
        }
    }


    public String getProductList(Map<String, Object> param, String coreAdminFacadeUrl) {

        JSONObject asJsonObject = getPostJsonObject(param, coreAdminFacadeUrl + getProductList);
        return Objects.isNull(asJsonObject.get(DATA)) ? null : asJsonObject.get(DATA).toString();
    }

    public String selectOrderByOnlyKey(String url, String onlyKey, Long tenantId) {

        HashMap<String, Object> param = new HashMap<>();
        param.put("onlyKey", onlyKey);
        param.put("tenantId", tenantId);
        JSONObject asJsonObject = getAsJsonObject(url + GET_ORDER_INFO, param);
        return Objects.isNull(asJsonObject.get(DATA)) ? null : asJsonObject.get(DATA).toString();

    }
}
